//
//  CLHomeTableViewController.swift
//  CLWeibo
//
//  Created by 陈亮 on 16/7/9.
//  Copyright © 2016年 陈亮. All rights reserved.
//

import UIKit
import SVProgressHUD
//重用标识符
private let homeIdentifier = "homeIdentifier"

class CLHomeTableViewController: CLVisitorTableViewController {

    //懒加载viewModel对象
    private lazy var statusListViewModel:CLStatusListViewModel = CLStatusListViewModel()
    //懒加载刷新控件
    private lazy var pullUpView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = UIColor.redColor()
    return view
        
    }()
    //懒加载tipLabel
    private lazy var tipLabel:UILabel = {
        let label = UILabel(textColor: UIColor.orangeColor(), fontSize: 12)
        label.backgroundColor = UIColor.redColor()
        label.textAlignment = .Center
        label.hidden = true
        return label
    }()
    //使用系统下拉刷新
//    private lazy var pullDownView:UIRefreshControl = {
//        let control = UIRefreshControl()
//        control.addTarget(self , action: "pullDownRefresh", forControlEvents:.ValueChanged)
//        return control
//    }()
    //使用自定义下拉刷新
    private lazy var pullDownView:CLRefreshControl = {
    
        let control = CLRefreshControl()
        control.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
        return control
    }()
    //下拉刷新
    @objc private func pullDownRefresh() {
        loadStatus()
    }
    private func endRefrshing() {
        //停止动画
        pullUpView.stopAnimating()
        pullDownView.endRefreshing()
    }
    //微博数据
//    var statusList:[CLStatus]?
    override func viewDidLoad() {
        super.viewDidLoad()

        if isLogin {
            loadStatus()
            registTableView()
            setUpUI()
        }else {
            visitorView?.updateVisitorInfo(nil , imageName: nil )
        }
        
    }
    //添加控件 设置约束
    private func setUpUI(){
        
        guard let nav = self.navigationController else {
            return
        }
        nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
        //设置frame 
        tipLabel.frame = CGRect(x: 0, y: 34, width: nav.navigationBar.width, height: 30)
    }
    // MARK:  开启tip动画
    private func startAnimation(message :String) {
        //注意:如果在执行动画  在动画未结束的时候  不需要再次执行动画 
        if tipLabel.hidden == false {
            //表示当前的 label的动画还没有结束
            return
        }
        //显示tipLabel
        tipLabel.hidden = false
        //设置tiplabel动画显示的内容
        tipLabel.text = message
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.tipLabel.transform = CGAffineTransformMakeTranslation(0, self.tipLabel.height)
            }) { (_) -> Void in
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.tipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        self.tipLabel.hidden = true
                })
        }
        
        
    }
    //注册
    private func registTableView (){
        tableView.registerClass(CLStatusTableViewCell.self , forCellReuseIdentifier: homeIdentifier)
        //设置自动适应行高
        tableView.rowHeight = UITableViewAutomaticDimension
        //预估高度
        tableView.estimatedRowHeight = 44
        tableView.separatorStyle = .None
        //下拉刷新
//        self.refreshControl = pullDownView
        tableView.addSubview(pullDownView)
        //指定footview为上拉加载
        tableView.tableFooterView = pullUpView
        pullUpView.sizeToFit()
    }
    //加载微博数据
    private func loadStatus(){
        
//        SVProgressHUD.show()
        
        statusListViewModel.loadData (pullUpView.isAnimating()) { (isSuccess,message ) -> () in
//            self.endRefrshing()
            if !self.pullUpView.isAnimating() {
               
                self.startAnimation(message)
            }
            //结束刷新
            self.endRefrshing()
            if isSuccess {
                self.tableView.reloadData()
            }
     
        }
        
    }
    
}
//
//        CLNetWorkingTool.sharedTool.loadStatus { (response, error) -> () in
//            if error != nil {
//                return
//            }
//            guard let dic = response as? [String:AnyObject] else {
//                return
//            }
//            guard let statsuDicArray = dic["statuses"] as? [[String :AnyObject]] else {
//                return
//            }
//            //遍历数组 完成字典转模型
//            //空的可变数组
//            var tempArray = [CLStatus]()
//            for statusDic in statsuDicArray {
//                let status = CLStatus(dic:statusDic)
//                tempArray.append(status)
//            }
//            self.statusList = tempArray
//            //刷新数据
//            self.tableView.reloadData()
//        }
        
//    }

//}
//tableView 数据源方法
extension CLHomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusList.count
        
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(homeIdentifier, forIndexPath: indexPath) as! CLStatusTableViewCell
        let statusViewModel = statusListViewModel.statusList[indexPath.row]
        cell.statusViewModel = statusViewModel
        
        return cell
        
    }
    
    
    //将要显示那个cell
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.row == statusListViewModel.statusList.count - 1 && !pullUpView.isAnimating() {
            pullUpView.startAnimating()
            loadStatus()
        }
        
    }
    
    
    
    
    
    
    
    
    
    
    
    
}
